#include "Task.hpp"
using namespace::std;
#define COMMAND_LOG 0;
#define COMMAND_NET 1;
#define COMMAND_MYSQL 2;
const int gum =5;
Task t;
void waitcommand()
{
    while(true)
    {
        int command;
        int len = read(0,&command,sizeof(int));
        if(len == sizeof(int))
        {
            t.execute(command);
        }
        else if(len == 0)
        {
            cout << len;
            break;
        }
        else
        {
            break;
        }
    }
}
void CreateProcess(vector<End_terminal>& End_terminals)
{
    for(int i=0;i<gum;i++)
    {
        int pipefd[2] = {0};
        int sign_pipe = pipe(pipefd);
        if(sign_pipe == -1)
        {
            cout<<"pipe-error" << errno << strerror(errno) <<endl;
        }
        pid_t son= fork();
        assert(!(son ==-1));
        if(son == 0)
        {
            dup2(pipefd[0],0);
            close(pipefd[1]);
            waitcommand();
            close(pipefd[0]);
            exit(0);
        }
        close(pipefd[0]);
        End_terminals.push_back(End_terminal(son,pipefd[1]));
    }
}
int main()
{
    vector<End_terminal> End_terminals;
    CreateProcess(End_terminals);
    while(true)
    {
        int command = rand()%t.funcs.size();
        int n = rand()%End_terminals.size();
        write(End_terminals[n]._write_fd,&command,sizeof(command));

        sleep(1);
    }
    return 0;
}